
/**
*@name 告警核心对象
*/
var publicAlarmObj={
	isWarnning:false, //是否告警
	isWorking:false,  //定时任务是否正在执行,默认设置为false
	// 告警有关标记
	alarmModelIdList: [], //告警模型ID列表
	alarmGlobalBuildingTagList: [], // 用于全景模型中，建筑的闪烁,应该存储的是全景模型中的建筑tag列表
	alarmDeviceIdList: [], //告警信息中设备id,用于告警定位，告警标记显示
	oldAlarmDeviceIdList:[],//老的告警设备ID数组
	warnModelMap:null,//
	alarmBuildingSummary:null, //按照大楼统计筛选后的告警统计
	isLock:false,
	lastDevPosModelId:'',//最近被定位的模型id
	lastDevPosDeviceId:'',//最近被定位的设备id
	//清除告警有关数据
	clearWarnData:function(){
		this.alarmModelIdList.length=0;
		this.alarmGlobalBuildingTagList.length=0;
		if (this.alarmDeviceIdList.length==0){
			this.oldAlarmDeviceIdList.length=0;
		}
		else{
		   this.oldAlarmDeviceIdList=this.alarmDeviceIdList.concat();//只能简单的数组复制
		}
		//注意被复制之后，才能被清空
		this.alarmDeviceIdList.length=0;
		
		//统计缓存设定为0
		if (this.alarmBuildingSummary==null){
			this.alarmBuildingSummary=new Map();
		}
		modelMap.globalBuildingTagIdList.forEach(function (item) {
			publicAlarmObj.alarmBuildingSummary.set(item,0);
		});
		this.alarmBuildingSummary.set('JG001',0);
		
	},
	/**
	*@author:luzhifei
	*@created:2019-09-03
	*@功能：创建告警标记。园区和多层模型的告警高度是特别设置的,楼层则位于设备上面100左右。
	*@param  scaleParam 放大参数
	*/
	createAlarmFlags:function(scaleParam){
		let modelAlarmHeight=null;
		if (modelMap.modelLevelName!='园区'){ 
			modelAlarmHeight=modelConfig.setting.alarmHeight;
		}
		for (x in this.alarmDeviceIdList){
			let item=this.alarmDeviceIdList[x];			
			let targetObj=g3d.dm().getDataByTag(item);
			if 	(targetObj!=undefined){
                if (modelMap.modelLevelName=='园区' || modelMap.modelLevelName=='building' ){
				    this.createFlag(targetObj.getPosition3d(),targetObj,true,scaleParam,modelAlarmHeight);
				}
				else{
					if (targetObj.getDisplayName()=="视频监控"){
					   modelAlarmHeight=targetObj.getPosition3d()[1]+100;
					}
					else{
					   modelAlarmHeight=targetObj.getPosition3d()[1]+300;	
					}
					this.createFlag(targetObj.getPosition3d(),targetObj,true,scaleParam,modelAlarmHeight);
				}
			}
		}
	},
	
    
	/**
	*@功能：设备的定位(告警/普通设备检索)
	*@param deviceId  被定位的设备id
	*@param isAlarm 是否告警
	*@Param scaleParam 告警标记放大倍数，默认只用于园区的非定位告警标记显示
	*@param alarmShowHeight 告警显示高度
	*@return 如果定位成功，则返回true，反之返回false
	*/
	positionDevice:function(deviceId,isAlarm,scaleParam,alarmShowHeight) {
		//创建标记
		var targetNode = g3d.dm().getDataByTag(deviceId);
		if (targetNode!=undefined){
			
			//清除旧的定位标记
			if (this.lastDevPosModelId!='' &&  this.lastDevPosModelId==modelMap.curModelId){
				this.clearPositionFlags(deviceId,isAlarm);
			}
		
		    //console.log(deviceId+"--- "+targetNode.getPosition3d()); 
			this.createFlag(targetNode.getPosition3d(),targetNode,isAlarm,scaleParam,alarmShowHeight);
			targetNode.setScale3d(modelConfig.scaleArr);
			targetNode.setStyle('body.color','red');
			//拉近设备
			let flyRation=modelConfig.flyRationNormal;
			if (modelMap.curModelId==modelMap.globalModelId){
				if (targetNode._displayName=='视频监控'){
					flyRation=modelConfig.flyRationGlobal;
				}
				else{
					flyRation=modelConfig.flyRationGlobalOther;
				}
				
			}
			let flyDirection=[0,5,5];  
			//正面查看（因为我们假定所有的设备都是只有那么几个角度,
			//且模型设备等等都是正常朝向z的正向
			//但由于设置的缘故，有多种模型并不是那么回事，所以，它们需要从背后看，才象正面
            let displayName=targetNode.getDisplayName();
			if (displayName=='对讲机'  ||   displayName=='限高报警' || 
			    displayName=='电子围栏' ||  displayName=='高压电网'  ){
				flyDirection=[0,5,-5];
			}
			
			g3d.flyTo(targetNode, 
			  {
				animation: true,
				direction:flyDirection,
				ratio: flyRation
			  }
			);
			
			this.lastDevPosDeviceId=deviceId;
			this.lastDevPosModelId=modelMap.curModelId;			
			return true;
			
		}
		else{
			return false;
		}
		
		
		
	},
 
	
	/**创建告警定位标记，或者设备定位标记
	*vm.warntipsdata3 表示当前的设备是否有告警
	*@param isAlarm 是否告警
	*@Param scaleParam 告警标记放大倍数，默认只用于园区的非定位告警标记显示
	*@param alarmShowHeight 告警显示高度
	*/
	createFlag:function(p3, host,isAlarm,scaleParam,alarmShowHeight,isPosition) {

		let modelAlarmHeight=alarmShowHeight;
		if (modelAlarmHeight==null){
			if (modelMap.curModelFileName=='园区'){
				if (host._displayName=='视频监控'){
					modelAlarmHeight=p3[1] + 100;
				}
				else{
					modelAlarmHeight=p3[1] + 300;
				}
				
			}
			else {
				//多层的以设置为准，单层的则以设备为准
				if (modelMap.modelLevelName=='building'){					
			       modelAlarmHeight=modelConfig.setting.alarmHeight*1;
				}
				else{
					if (host._displayName=='视频监控'){
						modelAlarmHeight=p3[1] + 100;
					}
					else{
						modelAlarmHeight=p3[1] + 300;
					}					
				}
				if (modelAlarmHeight==null || modelAlarmHeight==undefined || modelAlarmHeight==''){
					modelAlarmHeight=p3[1] + 100;
				}
			}
		}
		
		
		
		if (isAlarm==false){ //普通设备定位
		    let child=host.getAttaches();
			if (child!=undefined ){
				return;
			}
		    var node = new ht.Node();
			node.p3(p3[0], modelAlarmHeight, p3[2]);
			node.s({
				'shape3d': 'billboard',
				//'shape3d.image': 'no-alarm-circle',
				'shape3d.image': '/assets/devicePos.png',
				'3d.movable': false,
				'2d.movable': false,
				'3d.selectable': false,
				'shape3d.image.cache': true, // 是否缓存
				'shape3d.autorotate': true, // 始终面向相机
				"shape3d.transparent": true,
				'shape3d.alwaysOnTop': false, ////---- 是否需要一直在上方
				'shape3d.vector.dynamic': false,
				'shape3d.fixSizeOnScreen': false,
			});
			node.a('color', '#2ECCFA');//淡蓝色
			node.setHost(host)		
		    dataModel.add(node);
		}
		else{
			//判断当前是否已经有了,如果有，责不再加
			let child=host.getAttaches();
			if (child==undefined ){
				//console.log(host.getTag());
				var node = new ht.Node();
			    node.p3(p3[0], modelAlarmHeight, p3[2]);
				node.s({
					'shape3d': 'billboard',
					'shape3d.image': '/assets/alarmFlag.png',
					'3d.movable': false,
					'2d.movable': false,
					'3d.selectable': false,
					'shape3d.image.cache': true, // 是否缓存
					'shape3d.autorotate': true, // 始终面向相机
					"shape3d.transparent": true,
					'shape3d.alwaysOnTop': false, ////---- 是否需要一直在上方
					'shape3d.vector.dynamic': false,
					'shape3d.fixSizeOnScreen': false,
				});
				//node.a('color', '#ff0000');//红色
				if (scaleParam!=undefined && scaleParam!=null){
					node.setScale3d(scaleParam);
				}
                node.setHost(host)		
		        dataModel.add(node);			
                host.setStyle('body.color','yellow');				
			}
			else{
				host.getAttaches().get(0).s('shape3d.image','/assets/alarmFlag.png');
				//host.getAttaches().get(0).a('color', 'yellow');//黄色
			}
		}
		
		//return node;
	},
	/**
	*功能：获取统计信息
	*/
	getAlarmSummary:function(){
		$.ajax('/jg-api/alarm/getAlarmStats', {
				data: {},
				dataType: 'json',
				type: 'post',
				success: (res) => {
					if(res.success == true) {
					    for (j in  vm.warninfodata){
							let isFind=false;
							for (x in res.data){
								if (vm.warninfodata[j].id==res.data[x].deviceTypeId){
								   vm.warninfodata[j].num=res.data[x].amount;
								   isFind=true;
								   break;
								}
							}
							if (!isFind){
								vm.warninfodata[j].num=0;
							}
						    
						}
					} else {
						vm.$message(res.message);
					}
				}
		});
	},
	/**
	*@功能：刷新告警配置信息，包括 alarmModelIdList,alarmGlobalBuildingTagList
	*/
    fixalarmList:function() {
		this.isLock=true;		
        //重新按照大楼来统计筛选后的告警信息！
		
		/* for (x in this.alarmDeviceIdList){
			//注意：需要定时初始化alarmBuildingSummary,否则可能导致信息老化
			let modelId=this.alarmBuildingSummary.get(this.alarmDeviceIdList[x]);
			if (modelId==undefined){
				this.refreshRelatedInfo(this.alarmDeviceIdList[x]);
			}
			else{
				if (this.alarmModelIdList.indexOf(modelId)==-1){
					this.alarmModelIdList.push(modelId);
				}
			}
		} */
		//注意：以下循环和以上循环目前不能合并
		
		//刷新 告警设备tag - alarmGlobalBuildingTagList		
		for (x in this.alarmModelIdList){
			let underScoreIndex=this.alarmModelIdList[x].indexOf('_');
			if (underScoreIndex!=-1){//如果是楼层模型
				let topFlag=this.alarmModelIdList[x].slice(0,underScoreIndex);
				let topFlagIndex=this.alarmGlobalBuildingTagList.indexOf(topFlag);
				if (topFlagIndex==-1){					
					this.alarmGlobalBuildingTagList.push(topFlag);
				}
			}
		}
		
		this.isLock=false;
		
	},	
   /**
	*@author:luzhifei
	*@created :2019/09/10
	*功能：刷新告警闪烁信息--主要是建筑,并且如果建筑需要告警，则变为红色（但不是在这里闪烁）
	*@param alarmItem  可能来源于websocket推送的告警设备id,也可能是来源于  this.alarmDeviceIdList
	*/
	refreshRelatedInfo:function(alarmItem){		
	    $.ajax({
			url: '/jg-api/device/getDeviceInfo',
			type: 'post',
			async:false,
			data: {
				deviceId: alarmItem
			},
			success: function(res) {
				if (res.success === true) {
					publicAlarmObj.alarmBuildingSummary.set(alarmItem,res.data.modelId);
					if (publicAlarmObj.alarmModelIdList.indexOf(res.data.modelId)==-1){
						publicAlarmObj.alarmModelIdList.push(res.data.modelId);
					}					
				}
			}
		})
	},
    /**
    * 告警确认有关1
    */
	fixAlarm:function(alarm) {
		if (!alarm) return;
		alarm.split(',').length > 1 ? alarm = alarm.split(',') : alarm = alarm;
		if (Array.isArray(alarm)) {
			this.clearWarnData();
			if(map.isGlobalScene) {
				g3d.dm().each(function (data) {
					if (data._tag) {
						data.setStyle('body.color', undefined);
					}
				})
			}
		} else {
			this.alarmDeviceIdList = this.alarmDeviceIdList.filter(function (ele) {
				return ele !== alarm
			})
			this.fixalarmList();
		}
	},
	

	/**
	*@功能:清除模型上的告警标记图
	*@param  oldAlarmDeviceIdList  告警设备ID列表
	*@notice 暂时无用
	*/
	clearAlarmFlags:function(oldAlarmDeviceIdList){
		if (oldAlarmDeviceIdList!=null && oldAlarmDeviceIdList!=undefined){
			for (x in oldAlarmDeviceIdList){
				let item=oldAlarmDeviceIdList[x];			
				if (item!='园区' && item!='NaN'){
					let targetObj=g3d.dm().getDataByTag(item);
					if 	(targetObj){
						//TODO 确认如下方法
						targetObj.clearChildren();
					}
				}
		    }
		}
	},
	/**
	*@功能：清除设备定位标记
	*@注意：仅用于当前模型的重新定位的情况。
	*/
	clearPositionFlags:function(newDeviceId,isAlarm){
		if (this.lastDevPosDeviceId!=newDeviceId && this.lastDevPosDeviceId!=''){
			let posNode=g3d.dm().getDataByTag(this.lastDevPosDeviceId);
			if (posNode!=undefined){
				posNode.setStyle('body.color','');
				let child=posNode.getAttaches();
				if (child!=undefined ){
					if (isAlarm){
						child.get(0).a('color', 'red');
					}
					else{
					   //TODO，如果该位置是告警的，则不能移除掉
					   let nodeId=child.get(0).getId();
					   child.clear();
					   g3d.dm().removeDataById(nodeId);
					}
					
				}
		    }
	    }
	},
	/**
	*功能:刷新模型上的告警标记（图像)
	*@notice 暂时无用
	*/
	refreshAlarmFlags:function(oldAlarmDeviceIdList,newAlarmDeviceIdList){
		this.clearAlarmFlags(oldAlarmDeviceIdList);
		this.createAlarmFlags();		
	},
	refreshBuildingBillBoard:function(buildTag,showName){		
		/* let buildBoxNode=g3d.dm().getDataByTag(buildTag);
		if (buildBoxNode!=undefined){		   		   
		    let child=buildBoxNode.getAttaches();
			if (child!=undefined){
				if (child.length>0){
					let childId=child.get(0).getId();
					g3d.dm().removeDataById(childId);
			        child.clear();
				}
				
			}
			let bNode = new ht.Node();
			let hostPos=buildBoxNode.getPosition3d();
			bNode.p3(hostPos[0], hostPos[1]+2000, hostPos[2]);
			bNode.s({
				'shape3d': 'billboard',
				'shape3d.image':'globalBuildingBoardImage',
				'3d.movable': false,
				'2d.movable': false,
				'3d.selectable': false,
				'shape3d.image.cache': true, // 是否缓存
				'shape3d.autorotate': true, // 始终面向相机
				"shape3d.transparent": true,
				'shape3d.alwaysOnTop': false, ////---- 是否需要一直在上方
				'shape3d.vector.dynamic': false,
				'shape3d.fixSizeOnScreen': false,
			});			
			bNode.a('msg', showName);
			bNode.setScale3d([1.4,1.4,1.4]);
			bNode.setHost(buildBoxNode);
			dataModel.add(bNode);			   
		} */

	}
};